package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //首先获取查询的参数
        String key = (String) params.get("key");
        //创建一个查询条件
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<BrandEntity>();
        //判断是否为空
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(obj ->{
                obj.eq("brand_id",key).or().like("name",key);
            });
        }
        //执行查询
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params),queryWrapper);
        //进行返回
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(BrandEntity brand) {
        //保持更新字段的一致
        this.updateById(brand);
        //TODO 将来品牌数据更新也要将冗余字段进行更新
        if (!StringUtils.isEmpty(brand.getName())){
            //同步更新其他表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
        }

    }

}